import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [
      { id: 1, name: '张三', email: 'zhangsan@example.com', age: 25, active: true },
      { id: 2, name: '李四', email: 'lisi@example.com', age: 30, active: false },
      { id: 3, name: '王五', email: 'wangwu@example.com', age: 28, active: true }
    ],
    currentUser: null,
    loading: false
  }),

  getters: {
    activeUsers: (state) => state.users.filter(user => user.active),
    inactiveUsers: (state) => state.users.filter(user => !user.active),
    userCount: (state) => state.users.length,
    activeUserCount: (state) => state.users.filter(user => user.active).length,
    averageAge: (state) => {
      if (state.users.length === 0) return 0
      const totalAge = state.users.reduce((sum, user) => sum + user.age, 0)
      return Math.round(totalAge / state.users.length)
    }
  },

  actions: {
    async fetchUsers() {
      this.loading = true
      try {
        await new Promise(resolve => setTimeout(resolve, 1000))
        console.log('用户数据加载完成')
      } catch (error) {
        console.error('加载用户失败:', error)
      } finally {
        this.loading = false
      }
    },

    addUser(user) {
      const newUser = {
        id: Date.now(),
        ...user,
        active: true
      }
      this.users.push(newUser)
    },

    updateUser(id, updates) {
      const index = this.users.findIndex(user => user.id === id)
      if (index !== -1) {
        this.users[index] = { ...this.users[index], ...updates }
      }
    },

    deleteUser(id) {
      const index = this.users.findIndex(user => user.id === id)
      if (index !== -1) {
        this.users.splice(index, 1)
      }
    },

    toggleUserStatus(id) {
      const user = this.users.find(user => user.id === id)
      if (user) {
        user.active = !user.active
      }
    },

    setCurrentUser(user) {
      this.currentUser = user
    },

    clearCurrentUser() {
      this.currentUser = null
    }
  }
})
